<?php

namespace app\common\model\node;

use app\common\model\BaseModel;
use app\common\model\worker\CustomerAuthModel;
use helper\Arr;


class NodeModel extends BaseModel
{
    protected $table = 'node';


    /**
     * 节点类型
     * @return array
     */
    public function getNodeType(){
        $arr = [
            ['key'=>0,'name'=>'普通节点'],
            ['key'=>1,'name'=>'客户节点'],
            ['key'=>2,'name'=>'订单节点']
        ];
        return $arr;
    }

    public function _formatList($list)
    {
        $nodeIds = array_column($list,'id');
        $processList = NodeProcessModel::where('node_id','in',$nodeIds)->order('show_order asc')->select()->toArray();
        $processList = Arr::group($processList,'node_id');
        foreach ($list as $k=>$v){
            $v['process_list'] = $processList[$v['id']] ?? [];
            $list[$k] = $v;
        }
        return $list;
    }

    public function getNodeList($type){
        $list = $this->where('node_type',$type)->column('*','id');
        $list = empty($list)?[]:$this->_formatList($list);
        return $list;
    }

    /**
     * 添加
     * @param $data
     * @throws \Exception
     */
    public function add($data)
    {
        $info = $this->where('node_name',$data['node_name'])->where('node_type',$data['node_type'])->find();
        if(!empty($info)) exception('存在同名的节点配置');
        return self::create($data);
    }

    /**
     * 添加
     * @param $data
     * @throws \Exception
     */
    public function edit($data)
    {
        $info = $this->where('node_name',$data['node_name'])->where('node_type',$data['node_type'])->where('id','<>',$data['id'])->find();
        if(!empty($info)) exception('存在同名的节点配置');
        return self::update($data);
    }

    public function del($id){
        //todo 是否有正在进行的任务在使用该节点

    }


}
